package com.demo.aidlproject.ui.home;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.RemoteException;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.demo.aidlproject.ConnectionListener;
import com.demo.aidlproject.IMessageService;
import com.demo.aidlproject.IServiceManager;
import com.demo.aidlproject.MessageReciverLister;
import com.demo.aidlproject.R;
import com.demo.aidlproject.aidl.IConnectionService;
import com.demo.aidlproject.databinding.FragmentHomeBinding;
import com.demo.aidlproject.entity.ConnectInfo;
import com.demo.aidlproject.entity.MessageBean;
import com.demo.aidlproject.service.RemoteService;

public class HomeFragment extends Fragment implements View.OnClickListener {
    public static final String TAG=HomeFragment.class.getSimpleName();
    private HomeViewModel homeViewModel;
    private FragmentHomeBinding binding;
    private Handler handler=new Handler(Looper.getMainLooper());

    MessageReciverLister messageReciverLister =new MessageReciverLister.Stub() {
        @Override
        public void onMessageReciver(MessageBean msg) throws RemoteException {
            Log.e(TAG, "onMessageReciver: "+Thread.currentThread().getName()+",msg=="+msg );
        }
    };
    ConnectionListener connectionListener=new ConnectionListener.Stub() {
        @Override
        public void connectSuccess(ConnectInfo obj) throws RemoteException {
            Log.e(TAG, "connectSuccess: "+obj );

        }

        @Override
        public void connectFaile(ConnectInfo obj) throws RemoteException {
            Log.e(TAG, "connectFaile: "+obj );

        }
    };
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        homeViewModel = new ViewModelProvider(this).get(HomeViewModel.class);
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_home, container, false);
        obser();
        initView(binding.getRoot());
//        initBindService();
        return binding.getRoot();
    }
    private void obser(){
        homeViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override

            public void onChanged(@Nullable String s) {
                binding.textHome.setText(s);
            }
        });
    }
    private void initView(View root) {
        binding.btnBindService.setOnClickListener(this);
        binding.btnUnbindService.setOnClickListener(this);
        binding.btnConnect.setOnClickListener(this);
        binding.btnConnect.setOnClickListener(this);
        binding.btnDisconnect.setOnClickListener(this);
        binding.btnIsconnected.setOnClickListener(this);
        binding.btnSendMessage.setOnClickListener(this);
        binding.btnRegister.setOnClickListener(this);
        binding.btnUnregister.setOnClickListener(this);

    }
    private IServiceManager iServiceManagerProxy;
    private IConnectionService iConnectionServiceProxy;
    private IMessageService iMessageServiceProxy;
    private ServiceConnection remoteServiceConnction =new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            Log.e(TAG, "onServiceConnected: "+componentName );
            iServiceManagerProxy=IServiceManager.Stub.asInterface(iBinder);
            try {
                iConnectionServiceProxy =IConnectionService.Stub.asInterface(iServiceManagerProxy.getService(IConnectionService.class.getSimpleName()));
                iMessageServiceProxy=IMessageService.Stub.asInterface(iServiceManagerProxy.getService(IMessageService.class.getSimpleName()));
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.e(TAG, "onServiceDisconnected: "+componentName );

        }
    };
    private void initBindService(){
        Intent intent=new Intent(getActivity(), RemoteService.class);
        getActivity().bindService(intent, remoteServiceConnction, Context.BIND_AUTO_CREATE);
    }
    private void unBindService() {
        getActivity().unbindService(remoteServiceConnction);

    }
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_bindService:
                initBindService();
                break;
            case R.id.btn_unbindService:
                unBindService();
                break;
            case R.id.btn_connect:
                try {
                    iConnectionServiceProxy.connect(connectionListener);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.btn_disconnect:
                try {
                    iConnectionServiceProxy.disconnect();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                break;

            case R.id.btn_isconnected:
                try {
                    Toast.makeText(getActivity(), ""+ iConnectionServiceProxy.isConnected(), Toast.LENGTH_SHORT).show();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.btn_send_message:
                MessageBean msg=new MessageBean();
                msg.setContent("send message from main thread.");
                try {
                    iMessageServiceProxy.sendMessage(msg);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.btn_register:
                try {
                    iMessageServiceProxy.registerMessageReceiverListener(messageReciverLister);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }

                break;
            case R.id.btn_unregister:
                try {
                    iMessageServiceProxy.unRegisterMessageReceiverListener(messageReciverLister);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }

                break;
        }

    }

}